
import {  RequestOperate, ResponseOperate} from "./opearte";

type EventCallback = (...args: any[]) => void;

class EventBus {
    private events: Map<RequestOperate|ResponseOperate, EventCallback[]>;

    constructor() {
        this.events = new Map();
    }

    /**
     * 订阅事件
     * @param event 事件名称
     * @param callback 回调函数
     */
    on(event: RequestOperate|ResponseOperate, callback: EventCallback): void {
        if (!this.events.has(event)) {
            this.events.set(event, []);
        }
        this.events.get(event)?.push(callback);
    }

    /**
     * 发布事件
     * @param event 事件名称
     * @param args 传递给回调函数的参数
     */
    emit(event: RequestOperate|ResponseOperate, ...args: any[]): void {

        if (this.events.has(event)) {
            this.events.get(event)?.forEach(callback => {
                callback(...args);
            });
        }
    }

    /**
     * 取消订阅事件
     * @param event 事件名称
     * @param callback 回调函数
     */
    off(event: RequestOperate|ResponseOperate, callback: EventCallback): void {
        if (this.events.has(event)) {
            const callbacks = this.events.get(event) || [];
            const index = callbacks.indexOf(callback);
            if (index !== -1) {
                callbacks.splice(index, 1);
            }
        }
    }
}

// 导出单例
const eventBus = new EventBus();
export default eventBus;